package com.apes.fn.fico.invoiceApply.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.fico.invoiceApply.model.InvoiceApply;
import com.apes.fn.fico.invoiceApply.model.InvoiceApplyItem;
import com.apes.fn.fico.invoiceApply.repository.InvoiceApplyItemRepository;
import com.apes.fn.fico.invoiceApply.repository.InvoiceApplyRepository;
import com.apes.fn.scm.merchant.account.model.MerchantAccountSettlement;
import com.apes.fn.scm.merchant.account.model.SettlementExpenseItem;
import com.apes.fn.scm.merchant.account.repository.AccountSettlementRepository;
import com.apes.fn.scm.merchant.settlement.model.CostSummary;
import com.apes.fn.scm.merchant.settlement.model.MerchantExpenseItem;
import com.apes.fn.scm.merchant.settlement.model.MerchantSettlement;
import com.apes.fn.scm.merchant.settlement.repository.MerchantSettlementRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.repository.CustomRepository;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.Arith;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.LogicalUtil;
import com.apes.framework.util.Tools;
import com.apes.scm.account.account.model.InventoryMode;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import com.apes.scm.masterdata.party.model.Corporate;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.CorporateRepository;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.voucher.model.Voucher;
import com.apes.scm.voucher.repository.VoucherRepository;
import com.apes.scm.voucher.service.VoucherType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @BelongsProject: apes-server
 * @BelongsPackage: com.apes.fn.fico.invoiceApply.service
 * @ClassName: InvoiceApplyService
 * @Author: pyb
 * @Description: 发票申请服务层
 * @CreateTime: 2021-04-08 18:04
 * @Version: 1.0
 */
@Service("invoiceApplyService")
public class InvoiceApplyService extends DomainService {
    @Autowired
    InvoiceApplyRepository invoiceApplyRepository;

    @Autowired
    InvoiceApplyItemRepository invoiceApplyItemRepository;

    @Autowired
    MerchantSettlementRepository merchantSettlementRepository;

    @Autowired
    VoucherRepository voucherRepository;

    @Autowired
    PartyRoleRepository partyRoleRepository;

    @Autowired
    AccountSettlementRepository accountSettlementRepository;

    /**
     * 创建
     *
     * @param request
     * @return
     */
    public InvoiceApply save(SimpleRequest request) {
        InvoiceApply invoiceApply = request.getO(InvoiceApply.class);
        if (invoiceApply.getInvoiceApplyItems().isEmpty()) {
            throw new RuntimeException("明细不能为空");
        }
        invoiceApply.getInvoiceApplyItems().forEach(item -> {
            if (item.getPriceTotal() == 0){
                throw new RuntimeException("开票金额为0，不允许保存！");
            }
        });
        isNullInvoiceApply(invoiceApply);
        invoiceApply.setState("sent");
        invoiceApply.setTotalSaleAmount(Arith.round(invoiceApply.getTotalSaleAmount(),2));
        judgeInfo(invoiceApply);
        invoiceApply.computeAmt();
        //invoiceApply.setInvoiceApplyItems(invoiceApply.getInvoiceApplyItemsFilter());
        InvoiceApply apply = invoiceApplyRepository.saveAndFlush(invoiceApply);
        //发票申请制单写入对账单
        writeStatement(apply);
        return apply;
    }

    /**
     * 根据发票类型判断字段是否非空
     * @param invoiceApply
     * @return
     */
    public void isNullInvoiceApply(InvoiceApply invoiceApply){
        //判断增值税纸质专用发票
        if("001843".equals(invoiceApply.getInvoiceType().getId())){
            if(invoiceApply.getAddressAndPhone()==null || "".equals(invoiceApply.getAddressAndPhone())){
                throw new RuntimeException("发票地址及电话不能为空");
            }
            if(invoiceApply.getInvoiceTitle()==null || "".equals(invoiceApply.getInvoiceTitle())){
                throw new RuntimeException("发票名称不能为空");
            }
            if(invoiceApply.getInvoiceTaxNumber()==null || "".equals(invoiceApply.getInvoiceTaxNumber())){
                throw new RuntimeException("发票税号不能为空");
            }
            if(invoiceApply.getBankInfo()==null || "".equals(invoiceApply.getBankInfo())){
                throw new RuntimeException("发票银行账号及开户行不能为空");
            }
        }
        //判断增值税纸质普通发票
        if("001844".equals(invoiceApply.getInvoiceType().getId())){
            if(invoiceApply.getInvoiceTitle()==null || "".equals(invoiceApply.getInvoiceTitle())){
                throw new RuntimeException("发票名称不能为空");
            }
            if(invoiceApply.getInvoiceTaxNumber()==null || "".equals(invoiceApply.getInvoiceTaxNumber())){
                throw new RuntimeException("发票税号不能为空");
            }

        }
    }

    /**
     * 修改
     *
     * @param request
     * @return
     */
    public InvoiceApply update(SimpleRequest request) {
        isValid(request, invoiceApplyRepository);
        InvoiceApply invoiceApply = request.getO(InvoiceApply.class);
        if (invoiceApply.getInvoiceApplyItems().isEmpty()) {
            throw new RuntimeException("明细不能为空");
        }
        isNullInvoiceApply(invoiceApply);
        judgeInfo(invoiceApply);
        InvoiceApply oldInvoiceApply = invoiceApplyRepository.findOne(invoiceApply.getId());
        //清除对账单中的申请单号
        clearStatement(oldInvoiceApply);
        invoiceApply.computeAmt();
        invoiceApply.setTotalSaleAmount(Arith.round(invoiceApply.getTotalSaleAmount(),2));
        InvoiceApply apply = invoiceApplyRepository.saveAndFlush(invoiceApply);
        //发票申请制单写入对账单
        writeStatement(apply);
        return apply;
    }

    /**
     * 删除
     *
     * @param request
     * @return
     */
    public String delete(SimpleRequest request) {
        isValid(request, invoiceApplyRepository);
        InvoiceApply invoiceApply = request.getO(InvoiceApply.class);
        //清除对账单中的申请单号
        clearStatement(invoiceApply);
        invoiceApplyRepository.delete(invoiceApply);
        return "删除成功";
    }

    /**
     * 申请
     *
     * @param request
     * @return
     */
    public InvoiceApply apply(SimpleRequest request) {
        isValid(request, invoiceApplyRepository);
        InvoiceApply invoiceApply = request.getO(InvoiceApply.class);
        invoiceApply.setState("apply");
        invoiceApply.setApplyId(request.getPerson());
        invoiceApply.setApplyDate(new Date());
        invoiceApply.setActualInvoicedAmount(Arith.round(invoiceApply.getActualInvoicedAmount(),2));
        return invoiceApplyRepository.saveAndFlush(invoiceApply);
    }

    /**
     * 审核
     *
     * @param request
     * @return
     */
    public InvoiceApply approve(SimpleRequest request) {
        isValid(request, invoiceApplyRepository);
        InvoiceApply invoiceApply = request.getO(InvoiceApply.class);
        invoiceApply.setState("approve");
        invoiceApply.setApproveId(request.getPerson());
        invoiceApply.setApproveDate(new Date());
        return invoiceApplyRepository.saveAndFlush(invoiceApply);
    }

    /**
     * 核算
     *
     * @param request
     * @return
     */
    public InvoiceApply accounting(SimpleRequest request) {
        isValid(request, invoiceApplyRepository);
        InvoiceApply invoiceApply = request.getO(InvoiceApply.class);
        invoiceApply.setState("accounting");
        invoiceApply.setAccountingId(request.getPerson());
        invoiceApply.setAccountingDate(new Date());
        return invoiceApplyRepository.saveAndFlush(invoiceApply);
    }

    /**
     * 驳回
     *
     * @param request
     * @return
     */
    public InvoiceApply reject(SimpleRequest request) {
        isValid(request, invoiceApplyRepository);
        InvoiceApply invoiceApply = request.getO(InvoiceApply.class);
        invoiceApply.setState("sent");
        return invoiceApplyRepository.saveAndFlush(invoiceApply);
    }

    /**
     * 完成
     *
     * @param request
     * @return
     */
    public InvoiceApply done(SimpleRequest request) {
        isValid(request, invoiceApplyRepository);
        InvoiceApply invoiceApply = request.getO(InvoiceApply.class);
        invoiceApply.setState("done");
        if (invoiceApply.getInvoiceApplyItems().isEmpty() || invoiceApply.getInvoiceApplyItems().size() == 0) throw new RuntimeException("请全选开票明细！！！");
        //回写对账单
        InvoiceApply apply = invoiceApplyRepository.saveAndFlush(invoiceApply);
        apply.getInvoiceApplyItems().stream().map(InvoiceApplyItem::getStatementId).distinct().collect(Collectors.toList()).forEach(id -> {
            MerchantSettlement merchantSettlement = merchantSettlementRepository.findOne(id);
            if(merchantSettlement != null){
                List<String> ids = new ArrayList<>();
                if (!Tools.isNull(merchantSettlement.getInvoiceNumber())) {
                    ids = Stream.of(merchantSettlement.getInvoiceNumber().split(",")).collect(Collectors.toList());
                }
                ids.add(apply.getInvoiceNumber());
                merchantSettlement.setInvoiceNumber(ids.stream().filter(k -> !Tools.isNull(k)).collect(Collectors.joining(",")));
            } else {
                MerchantAccountSettlement accountSettlement = accountSettlementRepository.findOne(id);
                List<String> ids = new ArrayList<>();
                if (!Tools.isNull(accountSettlement.getInvoiceNumber())) {
                    ids = Stream.of(accountSettlement.getInvoiceNumber().split(",")).collect(Collectors.toList());
                }
                ids.add(apply.getInvoiceNumber());
                accountSettlement.setInvoiceNumber(ids.stream().filter(k -> !Tools.isNull(k)).collect(Collectors.joining(",")));
            }
        });
        return apply;
    }

    /**
     * 发票申请制单写入对账单
     *
     * @param invoiceApply
     */
    public void writeStatement(InvoiceApply invoiceApply) {
        invoiceApply.getInvoiceApplyItems().stream().map(InvoiceApplyItem::getStatementId).distinct().collect(Collectors.toList()).forEach(id -> {
            MerchantSettlement merchantSettlement = merchantSettlementRepository.findOne(id);
            if(merchantSettlement != null) {
                List<String> ids = new ArrayList<>();
                if (!Tools.isNull(merchantSettlement.getInvoiceApplyId())) {
                    ids = Stream.of(merchantSettlement.getInvoiceApplyId().split(",")).collect(Collectors.toList());
                }
                ids.add(invoiceApply.getId());
                merchantSettlement.setInvoiceApplyId(ids.stream().filter(k -> !Tools.isNull(k)).collect(Collectors.joining(",")).trim());
            } else {
                MerchantAccountSettlement accountSettlement = accountSettlementRepository.findOne(id);
                List<String> ids = new ArrayList<>();
                if (!Tools.isNull(accountSettlement.getInvoiceApplyId())) {
                    ids = Stream.of(accountSettlement.getInvoiceApplyId().split(",")).collect(Collectors.toList());
                }
                ids.add(invoiceApply.getId());
                accountSettlement.setInvoiceApplyId(ids.stream().filter(k -> !Tools.isNull(k)).collect(Collectors.joining(",")).trim());
            }

        });
    }

    /**
     * 清除写入对账单的申请单号
     *
     * @param invoiceApply
     */
    public void clearStatement(InvoiceApply invoiceApply) {
        invoiceApply.getInvoiceApplyItems().stream().map(InvoiceApplyItem::getStatementId).distinct().collect(Collectors.toList()).forEach(id -> {
            MerchantSettlement merchantSettlement = merchantSettlementRepository.findOne(id);
            if(merchantSettlement != null){
                List<String> ids = Stream.of(merchantSettlement.getInvoiceApplyId().split(",")).collect(Collectors.toList());
                ids.removeIf(i -> Objects.equals(invoiceApply.getId(), i));
                merchantSettlement.setInvoiceApplyId(ids.stream().filter(k -> !Tools.isNull(k)).collect(Collectors.joining(",")).trim());
            } else {
                MerchantAccountSettlement accountSettlement = accountSettlementRepository.findOne(id);
                List<String> ids = Stream.of(accountSettlement.getInvoiceApplyId().split(",")).collect(Collectors.toList());
                ids.removeIf(i -> Objects.equals(invoiceApply.getId(), i));
                accountSettlement.setInvoiceApplyId(ids.stream().filter(k -> !Tools.isNull(k)).collect(Collectors.joining(",")).trim());
            }
        });
    }


    /**
     * 对开票商户的财务信息做判断
     *
     * @param invoiceApply
     */
    public void judgeInfo(InvoiceApply invoiceApply) {

        if (Objects.equals(invoiceApply.getInvoiceType().getId(), "electronic")) {
            if (Tools.isNull(invoiceApply.getInvoiceTitle())) {
                throw new RuntimeException("请联系财务补全商户的财务信息");
            }
        } else {
            if (Tools.isNull(invoiceApply.getInvoiceTitle()) || Tools.isNull(invoiceApply.getInvoiceTaxNumber())  ) {
                throw new RuntimeException("请联系财务补全商户的财务信息");
            }
        }
    }

    /**
     * 获取对账单
     *
     * @param request
     * @return
     */
    public PageImpl getMerchantSettlements(SimpleRequest request) {
        List<Map> requests = request.get("condition");
        String field = (String) requests.stream().filter(x -> Objects.equals(x.get("field"), "merchant.id")).findFirst().get().get("value");
        String invoiceCategory = (String) requests.stream().filter(x -> Objects.equals(x.get("field"), "invoiceCategory")).findFirst().get().get("value");
        Date startDate = DateUtil.parse((String) requests.stream().filter(x -> Objects.equals(x.get("field"), "startDate")).findFirst().get().get("value"));
        Date endDate = DateUtil.parse((String) requests.stream().filter(x -> Objects.equals(x.get("field"), "endDate")).findFirst().get().get("value"));
        Page<Map> maps = merchantSettlementRepository.findByMerchantAndState(field, startDate, endDate, PageRequest.of(request.get("page"), request.get("size")));
        List<JSONObject> collect = maps.getContent().stream().map(map -> {
            JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(map));
            PartyRole partyRole = partyRoleRepository.findById(map.get("MERCHANT").toString()).get();
            jsonObject.put("id",map.get("ID"));
            jsonObject.put("state",map.get("STATE"));
            jsonObject.put("merchant",partyRole);
            jsonObject.put("invoiceCategory", invoiceCategory);
            jsonObject.put("reconcileBeginDate", map.get("reconcileBeginDate").toString());
            jsonObject.put("reconcileEndDate", map.get("reconcileEndDate").toString());
            return jsonObject;
        }).collect(Collectors.toList());
        return new PageImpl<>(collect, maps.getPageable(), maps.getTotalPages());
    }

    /**
     * 生成发票申请单
     *
     * @param request
     * @return
     */
    public InvoiceApply generateInvoiceApply(SimpleRequest request) {
        //处理传参
        JSONArray parameter = request.get("parameter");
        JSONObject parameterObj = parameter.getJSONObject(0);
        String companyId = parameterObj.getJSONObject("merchant").getString("id");
        String invoiceCategory = parameterObj.getString("invoiceCategory");
        //填充主表数据
        InvoiceApply invoiceApply = new InvoiceApply();
        invoiceApply.setCompany(SpringManager.getBean(PartyRoleRepository.class).findById(companyId).get());
        invoiceApply.setInvoiceCategory(SpringManager.getBean(EnumerationRepository.class).findOne(invoiceCategory));
        invoiceApply.setState("sent");
        processingDetailedData(parameter, companyId, invoiceCategory, invoiceApply);
        invoiceApply.computeAmt();
        return invoiceApply;
    }

    /**
     * 处理发票明细数据
     *
     * @param parameter
     * @param companyId
     * @param invoiceCategory
     * @param invoiceApply
     */
    public void processingDetailedData(JSONArray parameter, String companyId, String invoiceCategory, InvoiceApply invoiceApply) {
        List<InvoiceApplyItem> invoiceApplyItems = new ArrayList<>();
        //处理明细数据
        parameter.forEach(data -> {
            Date reconcileBeginDate = ((JSONObject) data).getDate("reconcileBeginDate");
            Date reconcileEndDate = ((JSONObject) data).getDate("reconcileEndDate");
            String statementId = ((JSONObject) data).getString("id");
            //获取往期发票明细
            List<InvoiceApplyItem> invoiceApplyItemList = invoiceApplyItemRepository.findByCompanyAndInvoiceCategoryAndStatementId(companyId, invoiceCategory, statementId);
            if (Objects.equals("accessories", invoiceCategory)) {
                // 配件取业务凭证
                List<Voucher> vouchers = new ArrayList<>();
                vouchers.addAll(getCurrentConsumeVoucher(companyId, reconcileBeginDate, reconcileEndDate));
                vouchers.addAll(getCurrentPurchaseVoucher(companyId, reconcileBeginDate,reconcileEndDate));
                vouchers.forEach(voucher -> voucher.getVoucherItems().forEach(item -> {
                    if (item.getPriceTotal() != 0) {
                        InvoiceApplyItem invoiceApplyItem = new InvoiceApplyItem();
                        invoiceApplyItem.setInvoiceApply(invoiceApply);
                        String salesOrganization = item.getVoucher().getPartner().getId();
                        PartyRole partyRole = SpringManager.getBean(PartyRoleRepository.class).findOne(salesOrganization.substring(1, 5));
                        if(Objects.nonNull(partyRole)){
                            Corporate byParty = SpringManager.getBean(CorporateRepository.class).findByParty(partyRole.getParty());
                            if (!StringUtils.isEmpty(byParty) && !(byParty.getOperation().getId().equals("001072") || byParty.getOperation().getId().equals("001661"))) return;
                            invoiceApplyItem.setSalesOrganization(salesOrganization.substring(1, 5));
                            invoiceApplyItem.setSettlePolicy(statementId);
                            invoiceApplyItem.setStatementId(statementId);
                            invoiceApplyItem.setOrigin(item.getVoucher().getOrigin());
                            invoiceApplyItem.setOriginBusinessType(item.getVoucher().getOriginBusinessType());
                            invoiceApplyItem.setSource(item.getVoucher().getInnerBusinessKey());
                            invoiceApplyItem.setSourceBusinessType(item.getVoucher().getInnerBusinessType());
                            invoiceApplyItem.setProduct(item.getProduct());
                            invoiceApplyItem.setProductGroup(item.getProduct().getProductGroup());
                            invoiceApplyItem.setUom(item.getUom());
                            invoiceApplyItem.setTax(item.getTax());
                            invoiceApplyItem.setPriceUnit(item.getPriceUnit());
                            invoiceApplyItem.setProductQty(item.getProductQty());
                            invoiceApplyItem.setPriceTotal(item.getPriceTotal());
                            invoiceApplyItems.add(invoiceApplyItem);
                        }
                    }
                }));
                //过滤往期发票
                invoiceApplyItemList.forEach(item -> invoiceApplyItems.removeIf((applyItem)
                        -> Objects.equals(applyItem.getStatementId(), item.getStatementId())
                        && Objects.equals(applyItem.getOrigin(), item.getOrigin())
                        && Objects.equals(applyItem.getOriginBusinessType(), item.getOriginBusinessType())
                        && Objects.equals(applyItem.getSource(), item.getSource())
                        && Objects.equals(applyItem.getSourceBusinessType(), item.getSourceBusinessType())
                        && Objects.equals(applyItem.getInvoiceApply().getInvoiceCategory().getId(), item.getInvoiceApply().getInvoiceCategory().getId())));
            } else {
                MerchantSettlement merchantSettlement = merchantSettlementRepository.findOne(statementId);
                InvoiceApplyItem invoiceApplyItem = new InvoiceApplyItem();
                invoiceApplyItem.setInvoiceApply(invoiceApply);

                invoiceApplyItem.setStatementId(statementId);
                invoiceApplyItem.setSalesOrganization("1007");
                invoiceApplyItem.setProject("平台服务费");
                invoiceApplyItem.setProjectFeeReceived(0);
                //根据往期发票取已开票金额
                double projectFeeReceived = invoiceApplyItemList.stream().mapToDouble(InvoiceApplyItem::getProjectFeeDeducted).sum();
                invoiceApplyItem.setProjectFeeReceived(projectFeeReceived);
                if(merchantSettlement != null){
                    invoiceApplyItem.setSettlePolicy(merchantSettlement.getId());
                    invoiceApplyItem.setOrigin(merchantSettlement.getId());
                    invoiceApplyItem.setOriginBusinessType(merchantSettlement.getInnerBusinessType());
                    //计算平台服务费
                    double platformServiceFee = merchantSettlement.getAdjustedPlatformServiceFee();
                    double otherFee = merchantSettlement.getCostSummaries().stream().filter(costSummary -> LogicalUtil.in(costSummary.getCostSummaryType().getId(), "quotationExpense", "supplyChainFee", "insuranceFee")).mapToDouble(CostSummary::getCurrentPeriodActualDeducted).sum();
                    double currentAmount = merchantSettlement.getMerchantExpenseItems().stream().filter(merchantExpenseItem -> merchantExpenseItem.getExpenseItem().getExpenseType().isInvoiceValid()).mapToDouble(MerchantExpenseItem::getCurrentAmount).sum();
                    double fee = Arith.round(Arith.add(Arith.add(platformServiceFee, currentAmount), otherFee),2);
                    invoiceApplyItem.setProjectFee(fee);
                    invoiceApplyItem.setPriceTotal(fee);
                    invoiceApplyItem.setProjectFeeDeducted(fee);
                    invoiceApplyItem.setProjectFeeDeducted(Arith.sub(fee, projectFeeReceived));
                } else {
                    MerchantAccountSettlement accountSettlement = accountSettlementRepository.findOne(statementId);
                    invoiceApplyItem.setSettlePolicy(accountSettlement.getId());
                    invoiceApplyItem.setOrigin(accountSettlement.getId());
                    invoiceApplyItem.setOriginBusinessType(accountSettlement.getInnerBusinessType());
                    //计算平台服务费
                    double fee = Arith.round(accountSettlement.getExpenseItems().stream().filter
                            (expenseItem -> expenseItem.getIncomeItem().getIncomeType().isInvoiceValid()).mapToDouble(SettlementExpenseItem::getCurrentAmount).sum(),2);
                    invoiceApplyItem.setProjectFee(fee);
                    invoiceApplyItem.setPriceTotal(fee);
                    invoiceApplyItem.setProjectFeeDeducted(fee);
                    invoiceApplyItem.setProjectFeeDeducted(Arith.sub(fee, projectFeeReceived));
                }
                if (invoiceApplyItem.getProjectFeeDeducted() != 0.0d) {
                    invoiceApplyItems.add(invoiceApplyItem);
                }

            }

        });
        invoiceApply.setInvoiceApplyItems(invoiceApplyItems);
    }

    /**
     * 数据是否合法
     *
     * @param request
     * @param repository
     */
    private void isValid(SimpleRequest request, CustomRepository repository) {
        Model oldModel = (Model) repository.findOne((String) request.get("id"));
        if (oldModel == null) throw new RuntimeException("单据【" + request.get("id") + "】在系统中不存在。");
        if (oldModel.getVersion() != (int) request.get("version")) throw new RuntimeException("记录已更新或已删除，请重新提交！");
    }


    /**
     * 获取当期寄售消耗凭证(供应商为A1001与K1002)
     *
     * @param merchantId
     * @param reconcileBeginDate
     * @param reconcileEndDate
     * @return
     */
    public List<Voucher> getCurrentConsumeVoucher(String merchantId, Date reconcileBeginDate, Date reconcileEndDate) {
        return voucherRepository.findByCompanyAndVoucherTypeAndPartner(merchantId, VoucherType.SUPPLIER_CONSUME, InventoryMode.IM_CONSIGN, reconcileBeginDate, getAddDay(reconcileEndDate));
    }

    /**
     * 获取当期采购凭证(供应商为A1001与K1002)
     *
     * @param merchantId
     * @param reconcileBeginDate
     * @param reconcileEndDate
     * @return
     */
    public List<Voucher> getCurrentPurchaseVoucher(String merchantId, Date reconcileBeginDate, Date reconcileEndDate) {
        return voucherRepository.findByCompanyAndVoucherTypeAndPartner(merchantId, VoucherType.SUPPLIER_PURCHASE, InventoryMode.IM_OWN, reconcileBeginDate, getAddDay(reconcileEndDate));
    }

    /**
     * 获取日期+1
     *
     * @param date
     * @return
     */
    public static Date getAddDay(Date date) {
        return DateUtil.add(date, Calendar.DAY_OF_MONTH, 1);
    }


}
